import {
  getGroupMemberList,
  signoutGroup,
  getOfficialGroupSwiper,
  groupQRcode,
  deleteGroup,
  directJoinGroup,
  groupCardWall
} from '../../apis/group';
import {
  getCardList
} from "../../apis/card";
import {
  globalData
} from '../../utils/request';
const app = getApp();

let scrollInterval = null;
let scrollTimeOut = null;

Page({
  data: {
    articleSwiper: 0,
    from: '',
    groupId: null,
    animationDuration: 0,
    titleTop: 0,
    titleHeight: 0,
    officialGroupSwiper: [],
    officialRecommendGroup: [],
    showModal: false,
    groupInfo: {},
    shareImage: '',
    cardWallList: [],
    cardWallPageNum: 1,
    cardWallTotal: 0,
    cardWallCurrent: 0,
    memberList: [],
    memberPageNum: 1,
    memberNum: 0,
    memberSwiperCurrent: 0,
    groupNoticeShow: false,
    noSelectShow: true
  },

  onLoad(options) {
    if (options.scene) {
      const scene = decodeURIComponent(options.scene);
      let arr = scene.split('&');
      options.groupId = arr[0].substr(3);
      wx.setStorageSync('selectGroup', JSON.stringify({
        groupId: options.groupId
      }));
      this.setData({
        ...options
      });
    };
    if (options.from === 'share') {
      wx.setStorageSync('selectGroup', JSON.stringify({
        groupId: options.groupId
      }));
    };
    wx.setNavigationBarTitle({
      title: ''
    });
  },
  onShow() {
    let group = JSON.parse(wx.getStorageSync('selectGroup'));
    this.setData({
      groupId: group.groupId
    });
    this.setData({
      cardWallList: [],
      cardWallPageNum: 1,
      cardWallCurrent: 0,
      memberList: [],
      memberPageNum: 1,
      memberSwiperCurrent: 0
    });
    if (!this.data.groupId) {
      this.setData({
        noSelectShow: true
      });
    } else {
      this.setData({
        noSelectShow: false
      });
      this.getMyCard();
      this.getOfficialInfo(this.data.groupId);
      this.getGroupMember(this.data.groupId, 1, 32);
      this.getBasicInfo(this.data.groupId);
      this.getGroupCardWall({
        groupId: this.data.groupId,
        pageNum: 1,
        pageSize: 25
      });
    };
  },
  onShareAppMessage() {
    let image = '';
    if (this.data.groupInfo.image === '') {
      image = '../../images/group_default_avatar.png';
    } else {
      image = !new RegExp('^https://').test(this.data.groupInfo.image) && !new RegExp('^http://').test(this.data.groupInfo.image) ? app.globalData.url + this.data.groupInfo.image : this.data.groupInfo.image;
    };
    return {
      title: this.data.groupInfo.title,
      path: `/pages/groupDetails/index?from=share&type=${this.data.type}&groupId=${this.data.groupId}`,
      imageUrl: this.data.shareImage
    }
  },

  onUnload() {
    clearInterval(scrollInterval);
    scrollInterval = null;
    clearTimeout(scrollTimeOut);
    scrollTimeOut = null;
  },

  // 获取群组成员列表
  getGroupMember(groupId, pageNum, pageSize) {
    getGroupMemberList(groupId, pageNum, pageSize).then(res => {
      if (res.data.code === 200) {
        let {
          rows,
          total
        } = res.data;
        rows.forEach(v => {
          if (!new RegExp('https://').test(v.avatar) && !new RegExp('http://').test(v.avatar)) v.avatar = app.globalData.url + v.avatar;
          if (v.imageList) v.imageList = v.imageList.map(val => {
            if (!new RegExp('https://').test(val) && !new RegExp('http://').test(val)) val = app.globalData.url + val;
            return val
          });
        });

        let handleArr = (arr) => {
          let smallArr = arr.splice(0, 16);
          if (smallArr.length === 0) {
            this.setData({
              memberList: this.data.memberList
            });
            return
          };
          this.data.memberList.push(smallArr);
          handleArr(arr);
        };
        handleArr(rows);

        this.setData({
          memberNum: total,
          showModal: false,
          showGroupBtn: globalData.checkIn
        });
      };
    });
  },

  // 获取自己的名片
  getMyCard() {
    getCardList({
      cardType: 1
    }).then(res => {
      if (res.data.code === 200) {
        let {
          rows
        } = res.data;
        this.setData({
          cardList: rows
        });
      };
    });
  },

  // 获取官方群信息
  getOfficialInfo(groupId) {
    getOfficialGroupSwiper(groupId).then(res => {
      if (res.data.code === 200) {
        let {
          bannerList,
          recommendGroupList,
          types
        } = res.data.data;
        bannerList.forEach(v => {
          if (!new RegExp('https://').test(v.image) && !new RegExp('http://').test(v.image)) v.image = app.globalData.url + v.image;
        });
        recommendGroupList.forEach(v => {
          if (!new RegExp('https://').test(v.image) && !new RegExp('http://').test(v.image)) v.image = app.globalData.url + v.image;
        });
        this.setData({
          officialGroupSwiper: bannerList,
          officialRecommendGroup: recommendGroupList,
          type: types == 1 ? 'official' : 'user'
        });
      };
    });
  },

  // 未加入群组时获取基本信息
  getBasicInfo(id) {
    groupQRcode(id).then(res => {
      if (res.data.code === 200) {
        let {
          data
        } = res.data;
        if (data.image !== '') data.image = !new RegExp('^https://').test(data.image) && !new RegExp('^http://').test(data.image) ? app.globalData.url + data.image : data.image;
        this.setData({
          groupInfo: data,
          showGroupBtn: globalData.checkIn
        });
        if (data.remark !== '') {
          this.setData({
            animationDuration: Math.ceil(data.remark.length / 10) * 5
          });
        };
        if (data.image !== '') {
          wx.getImageInfo({
            src: data.image,
            success: res => {
              let avatar = {
                path: res.path,
                width: res.width,
                height: res.height
              };
              this.canvasShareImage(avatar, data.title);
            }
          });
        } else {
          wx.getImageInfo({
            src: '../../images/group_default_avatar.png',
            success: res => {
              let avatar = {
                path: '/' + res.path,
                width: res.width,
                height: res.height
              };
              this.canvasShareImage(avatar, data.title);
            }
          });
        };
      } else if (res.data.code === 503) {
        this.setData({
          noSelectShow: true
        });
      };
    });
  },

  // 更多名片组
  moreCardGroup() {
    wx.navigateTo({
      url: '/pages/cardGroup/index'
    });
  },

  // 名片墙
  getGroupCardWall(data) {
    groupCardWall(data).then(res => {
      if (res.data.code === 200) {
        let {
          rows,
          total
        } = res.data;
        this.setData({
          cardWallTotal: total
        });
        rows.forEach(v => {
          v.avatar = !new RegExp('^https://').test(v.avatar) && !new RegExp('^http://').test(v.avatar) ? app.globalData.url + v.avatar : v.avatar;
          if (v.imageList) v.imageList = v.imageList.map(v => {
            return v = !new RegExp('^https://').test(v) && !new RegExp('^http://').test(v) ? app.globalData.url + v : v;
          });
        });

        let handleArr = (arr) => {
          let smallArr = arr.splice(0, 5);
          if (smallArr.length === 0) {
            this.setData({
              cardWallList: this.data.cardWallList
            });
            return
          };
          this.data.cardWallList.push(smallArr);
          handleArr(arr);
        };
        handleArr(rows);

        // arr.forEach(v => {
        //   this.data.cardWallList.push(v);
        // });
        // this.setData({
        //   cardWallList: this.data.cardWallList
        // });

        // if (this.data.cardWallList.length > 7 && scrollInterval === null) {
        //   scrollTimeOut = setTimeout(() => {
        //     scrollInterval = setInterval(() => {
        //       this.setData({
        //         scrollPostion: this.data.scrollPostion + 0.4
        //       });
        //     }, 10);
        //     clearTimeout(scrollTimeOut);
        //     scrollTimeOut = null;
        //   }, 500);
        // };
      };
    });
  },
  scrollLeft() {
    clearInterval(scrollInterval);
    scrollInterval = null;
    if (this.data.scrollDirection === 'left') {
      this.setData({
        scrollDirection: 'right'
      });
      scrollInterval = setInterval(() => {
        this.setData({
          scrollPostion: this.data.scrollPostion + 0.4
        });
      }, 10);
    };
  },
  scrollRight() {
    clearInterval(scrollInterval);
    scrollInterval = null;
    if (this.data.scrollDirection === 'right') {
      this.setData({
        scrollDirection: 'left'
      });
      scrollInterval = setInterval(() => {
        this.setData({
          scrollPostion: this.data.scrollPostion - 0.4
        });
      }, 10);
    }
  },
  bindScroll(e) {
    let {
      scrollLeft
    } = e.detail;
    if (scrollInterval === null) {
      this.setData({
        scrollPostion: scrollLeft
      });
    };
  },
  bindScrollStart() {
    clearInterval(scrollInterval);
    scrollInterval = null;
    clearTimeout(scrollTimeOut);
    scrollTimeOut = null;
  },
  bindScrollEnd() {
    if (this.data.cardWallList.length <= 7) return
    if (this.data.scrollDirection === 'left') {
      scrollTimeOut = setTimeout(() => {
        scrollInterval = setInterval(() => {
          this.setData({
            scrollPostion: this.data.scrollPostion - 0.4
          });
        }, 10);
      }, 1000);
    } else if (this.data.scrollDirection === 'right') {
      scrollTimeOut = setTimeout(() => {
        scrollInterval = setInterval(() => {
          this.setData({
            scrollPostion: this.data.scrollPostion + 0.4
          });
        }, 10);
      }, 1000);
    };
  },

  handleArr(arr) {
    let smallArr = arr.splice(0, 5);
    if (smallArr.length === 0) {
      this.setData({
        cardWallList: this.data.cardWallList
      });
      return
    };
    this.data.cardWallList.push(smallArr);
    this.handleArr(arr);
  },

  // 名片墙Swiper
  cardWallSwiperChange(e) {
    let {
      current
    } = e.detail;
    this.setData({
      cardWallCurrent: current
    });
    if (current == this.data.cardWallList.length - 2 && this.data.cardWallTotal > 50) {
      this.setData({
        cardWallPageNum: this.data.cardWallPageNum + 1
      });
      this.getGroupCardWall({
        groupId: this.data.groupId,
        pageNum: this.data.cardWallPageNum,
        pageSize: 25
      });
    } else if (current == this.data.cardWallList.length - 2 && this.data.cardWallTotal <= 50) {
      if (this.data.cardWallPageNum === 1 && this.data.cardWallTotal <= 25) return
      if (this.data.cardWallPageNum === 2) return
      this.setData({
        cardWallPageNum: this.data.cardWallPageNum + 1
      });
      let arr = new Array;
      this.data.cardWallList.forEach(v => {
        v.forEach(val => {
          arr.push(val.cardId);
        });
      });
      this.getGroupCardWall({
        groupId: this.data.groupId,
        pageNum: this.data.cardWallPageNum,
        pageSize: 25,
        cardIds: arr
      });
    }
  },
  // 成员Swiper
  memberSwiperChange(e) {
    let {
      current
    } = e.detail;
    this.setData({
      memberSwiperCurrent: current
    });
    if (current === this.data.memberList.length - 2) {
      let num = new Number;
      this.data.memberList.forEach(v => {
        num += v.length
      });
      if (num === this.data.memberNum) return
      this.setData({
        memberPageNum: this.data.memberPageNum + 1
      });
      this.getGroupMember(this.data.groupId, this.data.memberPageNum, 32);
    }
  },

  // 生成分享小卡片
  canvasShareImage(avatar, groupName) {
    let cvs = wx.createCanvasContext('share');
    cvs.drawImage('../../images/share_bg.png', 0, 0, 420, 336);
    cvs.save();
    cvs.beginPath();
    cvs.arc(210, 136, 54, 0, Math.PI * 2, false);
    cvs.clip();
    if (avatar.width > avatar.height) {
      cvs.drawImage(avatar.path, (avatar.width - avatar.height) / 2, 0, avatar.height, avatar.height, 156, 82, 108, 108);
    } else if (avatar.width < avatar.height) {
      cvs.drawImage(avatar.path, 0, (avatar.height - avatar.width) / 2, avatar.width, avatar.width, 156, 82, 108, 108);
    } else {
      cvs.drawImage(avatar.path, 156, 82, 108, 108);
    };
    cvs.restore();
    cvs.setFillStyle('#fff');
    cvs.setFontSize(30);
    let nameWidth = cvs.measureText(groupName).width;
    cvs.fillText(groupName, 210 - nameWidth / 2, 240);

    cvs.draw(false, () => {
      wx.canvasToTempFilePath({
        canvasId: 'share',
        destWidth: '420',
        destHeight: '336',
        fileType: 'png',
        success: res => {
          this.setData({
            shareImage: res.tempFilePath
          });
        }
      });
    });
  },
  // 用户信息
  bindgetuserinfo(e) {
    if (e.detail.userInfo) {
      app.globalData.userInfo = e.detail.userInfo;
      this.joinGroup();
    };
  },
  // 加入
  joinGroup() {
    if (this.data.cardList.length === 1) {
      if (this.data.groupInfo.checked == 1) {
        directJoinGroup(this.data.groupId, this.data.cardList[0].cardId).then(res => {
          if (res.data.code === 200) {
            this.onShow();
            // this.getOfficialInfo(this.data.groupId);
            // this.getGroupMember(this.data.groupId, 1, 32);
            // this.getBasicInfo(this.data.groupId);
            // this.getGroupCardWall({
            //   groupId: this.data.groupId,
            //   pageNum: 1,
            //   pageSize: 25
            // });
          };
        });
      } else {
        wx.navigateTo({
          url: `/pages/applyGroup/index?type=joinGroup&groupId=${this.data.groupId}&cardId=${this.data.cardList[0].cardId}`
        });
      };
    } else {
      wx.navigateTo({
        url: `/pages/myCard/index?type=joinGroup&groupId=${this.data.groupId}&checked=${this.data.groupInfo.checked}`
      });
    };
  },
  // 隐藏弹窗
  hideOverlay() {
    wx.switchTab({
      url: '/pages/mailList/index'
    });
  },

  goGroupMemberList() {
    wx.navigateTo({
      url: `/pages/editGroup/index?type=preview&groupId=${this.data.groupId}&isOfficial=${this.data.type==='official'?1:0}`
    });
  },

  // 更新名片
  updateMyCard() {
    wx.navigateTo({
      url: `/pages/myCard/index?type=updateGroupCard&groupId=${this.data.groupId}`
    });
  },
  modifyCard() {
    wx.navigateTo({
      url: `/pages/editCard/index?type=edit&cardId=${this.data.groupInfo.joinCardId}`
    });
  },

  // 退出群
  signoutGroup() {
    wx.showModal({
      content: '',
      title: '退出群组',
      success: res => {
        if (res.confirm) {
          signoutGroup(this.data.groupId, this.data.groupInfo.joinCardId).then(res => {
            if (res.data.code === 200) {
              wx.showToast({
                title: '退出成功',
                duration: 1500,
                icon: 'success',
                mask: true,
                success: res => {
                  let timer = setTimeout(() => {
                    wx.navigateBack({
                      delta: 1
                    });
                    clearTimeout(timer);
                  }, 1500);
                }
              });
            };
          });
        };
      }
    });
  },

  // 解散
  dismissGroup() {
    wx.showModal({
      title: '确定解散该群吗',
      success: res => {
        if (res.confirm) {
          deleteGroup(this.data.groupId).then(res => {
            if (res.data.code === 200) {
              wx.showToast({
                title: '解散成功',
                icon: 'success',
                mask: true,
                duration: 1500,
                success: res => {
                  setTimeout(() => {
                    wx.navigateBack({
                      delta: 1
                    });
                  }, 1500);
                }
              });
            };
          });
        };
      }
    });
  },

  // 查看名片墙
  previewCardWall(e) {
    let {
      index,
      iindex
    } = e.currentTarget.dataset;
    let card = this.data.memberList[index][iindex];
    wx.navigateTo({
      url: `/pages/groupCardPreview/index?type=group&groupId=${this.data.groupId}&card=${JSON.stringify(card)}&joinCardId=${this.data.groupInfo.joinCardId}`
    });
  },

  previewScrollCard(e) {
    let {
      index,
      iindex
    } = e.currentTarget.dataset;
    let card = this.data.cardWallList[index][iindex];
    wx.navigateTo({
      url: `/pages/groupCardPreview/index?type=group&groupId=${this.data.groupId}&card=${JSON.stringify(card)}&joinCardId=${this.data.groupInfo.joinCardId}`
    });
  },

  previewGroupNotice() {
    this.setData({
      groupNoticeShow: true
    });
  },
  hideGroupNotice() {
    this.setData({
      groupNoticeShow: false
    });
  },

  // 名片人气榜
  goCardWall() {
    wx.navigateTo({
      url: `/pages/cardWall/index?groupId=${this.data.groupId}`
    });
  },

  goSearch() {
    wx.navigateTo({
      url: `/pages/search/index?groupId=${this.data.groupId}&myCardId=${this.data.groupInfo.joinCardId}`
    });
  },

  // 前往推荐群
  goRecommendGroup(e) {
    let {
      index
    } = e.currentTarget.dataset;
    let group = this.data.officialRecommendGroup[index];
    wx.setStorageSync('selectGroup', JSON.stringify({
      groupId: group.groupId
    }));
    this.onShow();
    // wx.navigateTo({
    //   url: `/pages/groupDetails/index?type=official&groupId=${group.groupId}`
    // });
  },

  // 官方群查看轮播图
  previewSwiper(e) {
    let {
      path
    } = e.currentTarget.dataset;
    wx.navigateTo({
      url: '/' + path
    });
  },

  // 功能跳转
  actionJump(e) {
    let {
      type
    } = e.currentTarget.dataset;
    if (type === 'admin') {
      if (this.data.groupInfo.master) {
        wx.navigateTo({
          url: `/pages/createGroup/index?type=admin&groupId=${this.data.groupId}`
        });
      } else {
        wx.navigateTo({
          url: `/pages/createGroup/index?from=${this.data.type}&type=member&groupId=${this.data.groupId}`
        });
      };
    } else if (type === 'invite') {
      wx.navigateTo({
        url: `/pages/editGroup/index?type=invite&groupId=${this.data.groupId}&isMaster=${this.data.groupInfo.master}&isChecked=${this.data.groupInfo.checked}`
      });
    } else if (type === 'qrcode') {
      wx.navigateTo({
        url: `/pages/qrCode/index?type=group&groupId=${this.data.groupId}&from=${this.data.type}`
      });
    };
  },

  emptyFunction() {},

  goback() {
    if (this.data.from === 'share') {
      wx.switchTab({
        url: '/pages/mailList/index'
      });
    } else {
      wx.navigateBack({
        delta: 1
      });
    };
  }
})